﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ERPStore.Cart.Models
{
	public static class ModelExtentions
	{
		public static void PrepareToView(this ERPStore.Models.OrderCart cart, 
			ERPStore.Models.UserPrincipal principal, 
			ERPStore.Services.IOffersService offerService, 
			ERPStore.Services.ISalesService salesService, 
			ERPStore.Services.IAccountService accountService,
			ERPStore.Services.IIncentiveService incentiveService,
			ERPStore.Services.ICartService cartService
			)	
		{
			var user = principal.CurrentUser;

			foreach (var item in cart.Items)
			{
				offerService.ApplyOffers(item.Product, user);
			}
			// Affectation de l'adresse avant le calcul des frais
			if (user != null)
			{
				cart.DeliveryAddress = user.LastDeliveredAddress;
			}
			else
			{
				var registrationUser = accountService.GetRegistrationUser(cart.VisitorId);
				if (registrationUser != null)
				{
					cart.DeliveryAddress = registrationUser.GetShippingAddress();
					if (registrationUser.IsSameBillingAddress)
					{
						cart.BillingAddress = registrationUser.GetShippingAddress();
					}
				}
			}
			salesService.CalculateShippingFee(cart, principal);
			salesService.ProcessExport(cart, principal);
			cartService.ApplyProductStockInfoList(cart);
		}

		public static void PrepareToSerialize(this ERPStore.Models.OrderCart cart)
		{
			// Do nothing 
		}
	}
}
